#include "precompiled.h"
#pragma hdrstop

namespace inf {

    double Timer::base = -1.0;

    /*
    =================
    Timer::init_base_clock_ticks
    =================
    */
    void Timer::init_base_clock_ticks( void ) const {
        Timer timer;
        double ct, b;
        int i;

        base = 0.0;
        b = -1.0;
        for ( i = 0; i < 1000; i++ ) {
            timer.clear();
            timer.start();
            timer.stop();
            ct = timer.clock_ticks();
            if ( b < 0.0 || ct < b ) {
                b = ct;
            }
        }
        base = b;
    }

    TimeReport::TimeReport() {
    }

    TimeReport::~TimeReport() {
    }

    void TimeReport::SetReportName( const char *name ) {
        this->name = ( name ) ? name : "Timer Report";
    }

    int TimeReport::AddReport( const char *name ) {
        if ( name && *name ) {
            names.append( name );
            return timers.append( new inf::Timer() );
        }
        return -1;
    }

    Timer*     TimeReport::FindTimer( const char* name ) {
        for ( int i = 0; i < names.size(); i++ ) {
            if ( names[i].cmp( name, false ) == 0 ) {
                return timers[i];   // found!
            }
        }

        return NULL;
    }

    Timer*     TimeReport::GetTimer( int index ) {
        if( timers.size() <= index || index < 0 )
            return NULL;

        return timers[index];
    }

    void			TimeReport::Clear( void ) {
        inf::delete_contents( timers.begin(), timers.end(), true );
        names.clear();
    }

    void			TimeReport::Reset( void ) {
        assert ( timers.size() == names.size() );
        for ( int i = 0; i < timers.size(); i++ ) {
            timers[i]->clear();
        }
    }

    void			TimeReport::AddTime( const char *name, Timer *time ) {
        assert ( timers.size() == names.size() );
        int i;
        for ( i = 0; i < names.size(); i++ ) {
            if ( names[i].cmp( name, false ) == 0 ) {
                *timers[i] += *time;
                break;
            }
        }
        if ( i == names.size() ) {
            int index = AddReport( name );
            if ( index >= 0 ) {
                timers[index]->clear();
                *timers[index] += *time;
            }
        }
    }

}   // ::inf
